package com.jisu.controller;



import com.jisu.common.ResultVo;
import com.jisu.dto.ModelDTO;
import com.jisu.pojo.Model;
import com.jisu.service.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RefreshScope
public class ModelController {

    @Autowired
    private ModelService modelService;



    // 新增车辆信息
    @PostMapping("/addCar")
    public ResultVo addCar(@RequestBody Model model) {

        // 如果前端传递了 create_time，则使用传递的时间，否则使用当前时间
        if (model.getCreateTime() == null) {
            model.setCreateTime(LocalDateTime.now());
        }
        model.setUpdateTime(LocalDateTime.now());
        if (modelService.save(model)) {
            return ResultVo.success("添加成功",200);
        } else {
            return ResultVo.fail("添加失败",500);
        }


    }

    // 根据 ID 删除车辆
    // 支持批量删除车辆（通过路径参数传入多个 ID）
    @DeleteMapping("/deleteCarByIds/{ids}")
    public ResultVo deleteCar(@PathVariable List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return ResultVo.fail("未选中车辆！");
        }

        try {
            boolean deleteRows = modelService.removeBatchByIds(ids);
            if (deleteRows) {
                return ResultVo.success("删除成功");
            } else {
                return ResultVo.fail("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.fail("未知错误");
        }
    }

    // 更新车辆信息（根据路径中的 ID 更新指定车辆）
    @PutMapping("/updateCarById/{id}")
    public ResultVo updateCarById(@PathVariable Integer id, @RequestBody Model model) {
        Model existingModel = modelService.getById(id);
        if (existingModel == null) {
            return ResultVo.fail("车辆不存在");
        }

        // 更新时间戳
        model.setModelId(id); // 确保更新的是指定 ID 的记录
        model.setUpdateTime(LocalDateTime.now());

        try {
            boolean result = modelService.updateById(model);
            if (result) {
                return ResultVo.success("更新成功");
            } else {
                return ResultVo.fail("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.fail("未知错误");
        }
    }

    // 根据 ID 查询车辆信息
    @GetMapping("/getCarInfo")
    public Model getCarInfo(@RequestParam("id") Long id) {
        return modelService.getById(id);
    }


    // 根据 DTO 多条件查询车辆信息
    @GetMapping("/searchCarsByDTO")
    public ResultVo<List<Model>> searchCarsByDTO(ModelDTO modelDTO) {
        System.out.println("modelDTO = " + modelDTO);
        List<Model> cars = modelService.searchCarsByDTO(modelDTO);
        return ResultVo.success("查询成功", cars);
    }


}
